package weaver.interfaces.action;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.email.EmailWorkRunnable;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/2/22
 * @Description 考核结果异常邮件提醒
 * @Author AdminZm
 */
public class GradeAbnormalEmailAction implements Action {

    BaseBean baseBean = new BaseBean();

    @Override
    public String execute(RequestInfo requestInfo) {
        int billid = requestInfo.getRequestManager().getBillid();
        String requestId = requestInfo.getRequestid();
        String formtable = requestInfo.getRequestManager().getBillTableName();
        RecordSet rs = new RecordSet();
        String detailCount = baseBean.getPropValue("ss_prop_zm", "grade_workflow_detail_count");
        if (StringUtils.isEmpty(detailCount)) {
            detailCount = "5";
        }
        try {
            String szkhjh = "";
            rs.execute("SELECT szkhjh FROM " + formtable + " WHERE requestid = ?", requestId);
            if (rs.next()) {
                szkhjh = rs.getString("szkhjh");
            }
            baseBean.writeLog("GradeAbnormalEmailAction szkhjh is:" + szkhjh + "、" + requestId);
            String jxkhmc = "";
            if (StringUtils.isNotEmpty(szkhjh)) {
                rs.executeQuery("select id,jxhdmc from uf_HRJX_KHJH WHERE id = ?", szkhjh);
                if (rs.next()) {
                    jxkhmc = rs.getString("jxhdmc");
                }
            }
            String title = "绩效考核结果通知_" + jxkhmc;
            // 明细表中所有C/D的人员
            Set<String> resoueceIds = new HashSet<>();
            int dtCountInt = Integer.parseInt(detailCount);
            RecordSet rs1 = new RecordSet();
            List<Map<String, String>> roleMapList = new ArrayList<>();

            Map<String, List<Map<String, String>>> mapListMap = new HashMap<>();
            Map<String, Set<String>> setMap = new HashMap<>();

            // 从人事审批矩阵获取function head
            String matrixId = baseBean.getPropValue("ss_prop_zm", "hrm_sp_matrix_id");
            if (StringUtils.isEmpty(matrixId)) {
                matrixId = "4";
            }
            String functionheadSql = "SELECT functionalhead FROM matrixtable_" + matrixId + " WHERE bmmc = ?";
            baseBean.writeLog("functionheadSql is:" + functionheadSql);

            for (int i = 1; i <= dtCountInt; i++) {
                rs.executeQuery("SELECT * FROM " + formtable + "_dt" + i + " WHERE (dj = 3 or dj = 4) and mainid = ?", billid);
                while (rs.next()) {
                    String xm = rs.getString("xm");
                    String bm = rs.getString("bm");
                    String fp2 = rs.getString("fp2");
                    String dj = rs.getString("dj");
                    String gh = "";
                    String xmName = "";
                    String bmName = "";
                    String djName = "";
                    if (StringUtils.equals(dj, "3")) {
                        djName = "C";
                    }
                    if (StringUtils.equals(dj, "4")) {
                        djName = "D";
                    }
                    String MANAGERID = "";
                    rs1.executeQuery("SELECT workcode,lastname,MANAGERID FROM hrmresource where id = ?", xm);
                    if (rs1.next()) {
                        gh = rs1.getString("workcode");
                        xmName = rs1.getString("lastname");
                        MANAGERID = rs1.getString("MANAGERID");
                    }
                    rs1.executeQuery("SELECT departmentmark FROM hrmdepartment where id = ?", bm);
                    if (rs1.next()) {
                        bmName = rs1.getString("departmentmark");
                    }
                    Map<String, String> ygMap = new HashMap<>();
                    ygMap.put("gh", gh);
                    ygMap.put("xmName", xmName);
                    ygMap.put("bmName", bmName);
                    ygMap.put("df", fp2);
                    ygMap.put("djName", djName);
                    roleMapList.add(ygMap);

                    if (StringUtils.isNotEmpty(MANAGERID)) {
                        if (mapListMap.containsKey(MANAGERID)) {
                            List<Map<String, String>> mapList = mapListMap.get(MANAGERID);
                            Set<String> strings = setMap.get(MANAGERID);
                            if (CollectionUtils.isEmpty(strings)) {
                                strings = new HashSet<>();
                            }
                            if (!strings.contains(xm)) {
                                strings.add(xm);
                                mapList.add(ygMap);
                                setMap.put(MANAGERID, strings);
                                mapListMap.put(MANAGERID, mapList);
                            }
                        } else {
                            List<Map<String, String>> mapList = new ArrayList<>();
                            Set<String> strings = setMap.get(MANAGERID);
                            if (CollectionUtils.isEmpty(strings)) {
                                strings = new HashSet<>();
                            }
                            if (!strings.contains(xm)) {
                                strings.add(xm);
                                mapList.add(ygMap);
                                setMap.put(MANAGERID, strings);
                                mapListMap.put(MANAGERID, mapList);
                            }
                        }
                    }
                    rs1.executeQuery(functionheadSql, bm);
                    if (rs1.next()) {
                        String functionalhead = rs1.getString("functionalhead");
                        if (StringUtils.isNotEmpty(functionalhead)) {
                            String[] fArr = functionalhead.split(",");
                            for (String fid : fArr) {
                                if (mapListMap.containsKey(fid)) {
                                    List<Map<String, String>> mapList = mapListMap.get(fid);
                                    Set<String> strings = setMap.get(fid);
                                    if (CollectionUtils.isEmpty(strings)) {
                                        strings = new HashSet<>();
                                    }
                                    if (!strings.contains(xm)) {
                                        strings.add(xm);
                                        mapList.add(ygMap);
                                        setMap.put(fid, strings);
                                        mapListMap.put(fid, mapList);
                                    }
                                } else {
                                    List<Map<String, String>> mapList = new ArrayList<>();
                                    Set<String> strings = setMap.get(fid);
                                    if (CollectionUtils.isEmpty(strings)) {
                                        strings = new HashSet<>();
                                    }
                                    if (!strings.contains(xm)) {
                                        strings.add(xm);
                                        mapList.add(ygMap);
                                        setMap.put(fid, strings);
                                        mapListMap.put(fid, mapList);
                                    }
                                }
                            }
                        }
                    }
                    resoueceIds.add(xm);
                }
            }
            if (CollectionUtils.isEmpty(resoueceIds)) {
                baseBean.writeLog("no person id C or D.");
                return Action.SUCCESS;
            }

            // 发送给管理员
            if (!CollectionUtils.isEmpty(roleMapList)) {
                String roleName = "绩效异常通知角色";
                Set<String> roleEmailSet = new HashSet<>();
                rs.executeQuery("SELECT RESOURCEID FROM hrmrolemembers WHERE ROLEID = (SELECT ID FROM hrmroles WHERE ROLESMARK = ?)", roleName);
                while (rs.next()) {
                    String id = rs.getString("RESOURCEID");
                    rs1.executeQuery("SELECT email FROM hrmresource where id = ?", id);
                    if (rs1.next()) {
                        String emailTemp = rs1.getString("email");
                        if (StringUtils.isNotEmpty(emailTemp)) {
                            roleEmailSet.add(emailTemp);
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(roleEmailSet)) {
                    String roleEmails = "";
                    for (String e : roleEmailSet) {
                        roleEmails = roleEmails + e + ",";
                    }
                    if (StringUtils.isNotEmpty(roleEmails)) {
                        roleEmails = roleEmails.substring(0, roleEmails.length() - 1);
                        Map<String, String> paramMap = new HashMap<>();
                        paramMap.put("email", roleEmails);
                        String content = "<div class=\"ace-line ace-line old-record-id-WvbadzFapo7ebzxxPr1c12c5nzb\">&nbsp; &nbsp; &nbsp; <span class=\"ace-line ace-line old-record-id-IYoydsDFAojbogxVbXmcuPwInwd\"><span data-docx-has-block-data=\"true\" data-page-id=\"AaY0dpf3Qo1MZqxZpFbc5FXdnpd\">本</span>次绩效考核结果如下：</span></div>\n" +
                                "\n" +
                                "<div>\n" +
                                "<table class=\"ace-table\" data-ace-table-col-widths=\"100;100;117;143;123;136;100\" style=\"border: none; border-collapse: collapse; table-layout: fixed; width: 921px;\">\n" +
                                "\t<colgroup>\n" +
                                "\t\t<col width=\"100\" />\n" +
                                "\t\t<col width=\"100\" />\n" +
                                "\t\t<col width=\"117\" />\n" +
                                "\t\t<col width=\"143\" />\n" +
                                "\t\t<col width=\"123\" />\n" +
                                "\t\t<col width=\"136\" />\n" +
                                "\t\t<col width=\"100\" />\n" +
                                "\t</colgroup>\n" +
                                "\t<tbody>\n" +
                                "\t\t<tr style=\"height:39px;\">\n" +
                                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                                "\t\t\t<div class=\"ace-line ace-line old-record-id-DZ8mdpOfQoWib4xXsMocEkKqnyh\" style=\"text-align: center;\">工号</div>\n" +
                                "\t\t\t</td>\n" +
                                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                                "\t\t\t<div class=\"ace-line ace-line old-record-id-Dzj2dm9JSos5DpxqKBZcmrqNn0f\" style=\"text-align: center;\">姓名</div>\n" +
                                "\t\t\t</td>\n" +
                                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border: 1px solid rgb(222, 224, 227); font-size: 10pt; padding: 8px; vertical-align: top; text-align: center;\">部门名称</td>\n" +
                                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                                "\t\t\t<div class=\"ace-line ace-line old-record-id-Gl1gdCtKOoWcx4x06NScmLMinOd\" style=\"text-align: center;\">等分</div>\n" +
                                "\t\t\t</td>\n" +
                                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border: 1px solid rgb(222, 224, 227); font-size: 10pt; padding: 8px; vertical-align: top; width: 123px;\">\n" +
                                "\t\t\t<div class=\"ace-line ace-line old-record-id-HuUAdpcX9o3orgxyZv0c6egFnwe\" style=\"text-align: center;\">等级</div>\n" +
                                "\t\t\t</td>\n" +
                                "\t\t</tr>";
                        StringBuilder sfBegin = new StringBuilder(content);
                        for (Map<String, String> mapTemp : roleMapList) {
                            sfBegin.append(handleStr(mapTemp));
                        }
                        sfBegin.append("</tbody>\n" +
                                "</table>\n" +
                                "</div>\n" +
                                "</div>");
                        paramMap.put("content", sfBegin.toString());
                        paramMap.put("title", title);
                        sendEmail(paramMap);
                    }
                }
            }

            // 发送给上级或者functionalhead
            if (!CollectionUtils.isEmpty(mapListMap)) {
                for (Map.Entry<String, List<Map<String, String>>> mapListTemp : mapListMap.entrySet()) {
                    String key = mapListTemp.getKey();
                    List<Map<String, String>> value = mapListTemp.getValue();
                    if (CollectionUtils.isEmpty(value)) {
                        continue;
                    }
                    rs1.executeQuery("SELECT email FROM hrmresource where id = ?", key);
                    String emailTemp = "";
                    if (rs1.next()) {
                        emailTemp = rs1.getString("email");
                    }
                    if (StringUtils.isEmpty(emailTemp)) {
                        continue;
                    }
                    Map<String, String> paramMap = new HashMap<>();
                    paramMap.put("email", emailTemp);
                    String content = "<div class=\"ace-line ace-line old-record-id-WvbadzFapo7ebzxxPr1c12c5nzb\">&nbsp; &nbsp; &nbsp; <span class=\"ace-line ace-line old-record-id-IYoydsDFAojbogxVbXmcuPwInwd\"><span data-docx-has-block-data=\"true\" data-page-id=\"AaY0dpf3Qo1MZqxZpFbc5FXdnpd\">请关注本次绩效考核结果存在下属为特殊等级</span>：</span></div>\n" +
                            "\n" +
                            "<div>\n" +
                            "<table class=\"ace-table\" data-ace-table-col-widths=\"100;100;117;143;123;136;100\" style=\"border: none; border-collapse: collapse; table-layout: fixed; width: 921px;\">\n" +
                            "\t<colgroup>\n" +
                            "\t\t<col width=\"100\" />\n" +
                            "\t\t<col width=\"100\" />\n" +
                            "\t\t<col width=\"117\" />\n" +
                            "\t\t<col width=\"143\" />\n" +
                            "\t\t<col width=\"123\" />\n" +
                            "\t\t<col width=\"136\" />\n" +
                            "\t\t<col width=\"100\" />\n" +
                            "\t</colgroup>\n" +
                            "\t<tbody>\n" +
                            "\t\t<tr style=\"height:39px;\">\n" +
                            "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                            "\t\t\t<div class=\"ace-line ace-line old-record-id-DZ8mdpOfQoWib4xXsMocEkKqnyh\" style=\"text-align: center;\">工号</div>\n" +
                            "\t\t\t</td>\n" +
                            "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                            "\t\t\t<div class=\"ace-line ace-line old-record-id-Dzj2dm9JSos5DpxqKBZcmrqNn0f\" style=\"text-align: center;\">姓名</div>\n" +
                            "\t\t\t</td>\n" +
                            "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border: 1px solid rgb(222, 224, 227); font-size: 10pt; padding: 8px; vertical-align: top; text-align: center;\">部门名称</td>\n" +
                            "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                            "\t\t\t<div class=\"ace-line ace-line old-record-id-Gl1gdCtKOoWcx4x06NScmLMinOd\" style=\"text-align: center;\">等分</div>\n" +
                            "\t\t\t</td>\n" +
                            "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border: 1px solid rgb(222, 224, 227); font-size: 10pt; padding: 8px; vertical-align: top; width: 123px;\">\n" +
                            "\t\t\t<div class=\"ace-line ace-line old-record-id-HuUAdpcX9o3orgxyZv0c6egFnwe\" style=\"text-align: center;\">等级</div>\n" +
                            "\t\t\t</td>\n" +
                            "\t\t</tr>";
                    StringBuilder sfBegin = new StringBuilder(content);
                    for (Map<String, String> mapTemp : value) {
                        sfBegin.append(handleStr(mapTemp));
                    }
                    sfBegin.append("</tbody>\n" +
                            "</table>\n" +
                            "</div>\n" +
                            "</div>");
                    paramMap.put("content", sfBegin.toString());
                    paramMap.put("title", title);
                    sendEmail(paramMap);
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("GradeAbnormalEmailAction error:" + e.getMessage());
        }
        return Action.SUCCESS;
    }

    public Map<String, Object> sendEmail(Map<String, String> paramMap) {
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            String email = paramMap.get("email");
            String title = paramMap.get("title");
            //发送邮件内容
            String sendEmailContent = paramMap.get("content");
            EmailWorkRunnable ewr = new EmailWorkRunnable(email, title, sendEmailContent);
            boolean result = ewr.emailCommonRemind();
            resultMap.put("sendState", result);
            baseBean.writeLog(this.getClass().getName() + "-email-" + result);
        } catch (Exception e) {
            resultMap.put("errMsg", e.getMessage());
        }
        return resultMap;
    }

    public String handleStr(Map<String, String> map) {
        return "<tr style=\"height:39px;\">\n" +
                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                "\t\t\t<div class=\"ace-line ace-line old-record-id-JEmadRBGxoYmdLxkSJDcmiitnlN\" style=\"text-align: center;\">" + map.get("gh") + "</div>\n" +
                "\t\t\t</td>\n" +
                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                "\t\t\t<div class=\"ace-line ace-line old-record-id-O0UUdsTfBoQ1Ktxh7D6c0RKAnGf\" style=\"text-align: center;\">" + map.get("xmName") + "</div>\n" +
                "\t\t\t</td>\n" +
                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                "\t\t\t<div class=\"ace-line ace-line old-record-id-YMOQdHClFoWnERxXiuVckGObnKb\" style=\"text-align: center;\">" + map.get("bmName") + "</div>\n" +
                "\t\t\t</td>\n" +
                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border:1px solid rgb(222, 224, 227);font-size:10pt;padding:8px;vertical-align:top;\">\n" +
                "\t\t\t<div class=\"ace-line ace-line old-record-id-DJlGdQfS7opJWnxe8Uic6P0anlh\" style=\"text-align: center;\">" + map.get("df") + "</div>\n" +
                "\t\t\t</td>\n" +
                "\t\t\t<td colspan=\"1\" rowspan=\"1\" style=\"border: 1px solid rgb(222, 224, 227); font-size: 10pt; padding: 8px; vertical-align: top; width: 123px;\">\n" +
                "\t\t\t<div class=\"ace-line ace-line old-record-id-LOMrduX8ropSv6xslKJcN4van1m\" style=\"text-align: center;\">" + map.get("djName") + "</div>\n" +
                "\t\t\t</td>\n" +
                "\t\t</tr>";
    }
}
